package com.cjm.algorithm.leetcode;

import java.util.*;
import java.util.stream.Collectors;

public class GroupAnagrams49 {
    public static List<List<String>> groupAnagrams(String[] strs) {
        return new ArrayList<>(Arrays.stream(strs).collect(Collectors.groupingBy(str -> {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            return new String(chars);
        })).values());
    }

    public static List<List<String>> groupAnagrams1(String[] strs) {
        return new ArrayList<>(
                Arrays.stream(strs).collect(
                        Collectors.groupingBy(
                                str ->
                                        str.chars().sorted()
                                                .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString()
                        )
                ).values()
        );
    }

    public static List<List<String>> groupAnagrams2(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (int i = 0; i < strs.length; i++) {
            String str = strs[i];
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);
            List<String> orDefault = map.getOrDefault(key, new ArrayList<>());
            orDefault.add(str);
            map.put(key, orDefault);
        }
        return new ArrayList<>(map.values());
    }
}
